package com.wltt.product.ahuthr.service;

import com.wltt.product.ahuthr.component.SystemUserComponent;
import com.wltt.product.ahuthr.config.exception.BusinessException;
import com.wltt.product.ahuthr.enums.SystemUserStatusEnum;
import com.wltt.product.ahuthr.mapper.SystemDeptMapper;
import com.wltt.product.ahuthr.mapper.SystemUserMapper;
import com.wltt.product.ahuthr.model.ResultData;
import com.wltt.product.ahuthr.model.po.CurrentUserInfoBO;
import com.wltt.product.ahuthr.model.po.SystemDeptPO;
import com.wltt.product.ahuthr.model.po.SystemUserPO;
import com.wltt.product.ahuthr.model.vo.ActivateReq;
import com.wltt.product.ahuthr.model.vo.CurrentUserInfoRsp;
import com.wltt.product.ahuthr.model.vo.LoginReq;
import com.wltt.product.ahuthr.model.vo.RegisterSystemUserReq;
import com.wltt.product.ahuthr.service.base.BaseServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;


/**
 * @ClassName: SystemUserServiceImpl
 * @Description: 逻辑服务类<br />
 * 不做业务校验，参数校验统一放到前置的Service中
 * @Date: 2024-08-23 18:11:07
 * @Author yanggl
 */
@Service(value = "systemUserService")
public class SystemUserServiceImpl extends BaseServiceImpl<SystemUserPO, Long> implements SystemUserService {

    private SystemUserMapper systemUserMapper;

    @Resource
    private SystemDeptMapper systemDeptMapper;

    @Resource
    private SystemUserComponent systemUserComponent;

    //构造方法
    public SystemUserServiceImpl(SystemUserMapper systemUserMapper) {
        super(systemUserMapper);
        this.systemUserMapper = systemUserMapper;
    }

    /**
     * 注册
     *
     * @param registerSystemUserReq
     * @return
     */
    @Override
    @Transactional
    public ResultData register(RegisterSystemUserReq registerSystemUserReq) throws NoSuchAlgorithmException {
        Long systemDeptId = registerSystemUserReq.getSystemDeptId();
        if (null == systemDeptId) {
            throw new BusinessException("未指定部门", HttpStatus.BAD_REQUEST);
        }
        String userName = registerSystemUserReq.getUserName();
        if (null == userName) {
            throw new BusinessException("未指定姓名", HttpStatus.BAD_REQUEST);
        }
        String userAccount = registerSystemUserReq.getUserAccount();
        if (null == userAccount) {
            throw new BusinessException("未指定账号", HttpStatus.BAD_REQUEST);
        }

        SystemDeptPO systemDeptPO = systemDeptMapper.queryById(systemDeptId);
        if (null == systemDeptPO) {
            throw new BusinessException("部门不存在", HttpStatus.BAD_REQUEST);
        }

        SystemUserPO systemUserPO = systemUserMapper.queryByAccount(userAccount);
        if (null != systemUserPO) {
            if (SystemUserStatusEnum.RETESTED.getCode() == systemUserPO.getUserStatus()) {
                throw new BusinessException("改账户已经注册请登录激活", HttpStatus.BAD_REQUEST);
            }
            throw new BusinessException("改账户已经存在，请尝试其他账户", HttpStatus.BAD_REQUEST);
        }

        systemUserPO = new SystemUserPO();
        systemUserPO.setSystemDeptId(systemDeptId);
        systemUserPO.setUserAccount(userAccount);
        systemUserPO.setUserName(userName);
        systemUserPO.setUserStatus(SystemUserStatusEnum.UNACTIVATED.getCode());
        systemUserComponent.setPassword(systemUserPO);
        systemUserMapper.insertSelective(systemUserPO);
        return ResultData.success();
    }

    /**
     * 登录
     *
     * @param loginReq
     * @return
     */
    @Override
    public ResultData login(HttpServletRequest request, LoginReq loginReq) throws NoSuchAlgorithmException {
        String account = loginReq.getAccount();
        if (null == account) {
            throw new BusinessException("请填写账户", HttpStatus.BAD_REQUEST);
        }
        String password = loginReq.getPassword();
        if (null == password) {
            throw new BusinessException("请填写密码", HttpStatus.BAD_REQUEST);
        }
        SystemUserPO systemUserPO = systemUserMapper.queryByAccount(account);
        if (null == systemUserPO) {
            throw new BusinessException("账户密码错误", HttpStatus.BAD_REQUEST);
        }

        // 如果账户存在，校验密码是否正确
        if (!systemUserComponent.checkPassword(password, systemUserPO)) {
            throw new BusinessException("账户密码错误", HttpStatus.BAD_REQUEST);
        }

        if (SystemUserStatusEnum.LOCKED.getCode() == systemUserPO.getUserStatus()) {
            throw new BusinessException("账户已锁定", HttpStatus.BAD_REQUEST);
        }
        if (SystemUserStatusEnum.FORBIDDEN.getCode() == systemUserPO.getUserStatus()) {
            throw new BusinessException("账户已永久封禁", HttpStatus.BAD_REQUEST);
        }

        // 登录成功
        systemUserComponent.loginSuccess(request, systemUserPO);

        // 如果密码正确，验证账户状态
        if (SystemUserStatusEnum.RETESTED.getCode() == systemUserPO.getUserStatus()
                || SystemUserStatusEnum.UNACTIVATED.getCode() == systemUserPO.getUserStatus()) {
            throw new BusinessException("账户需要激活", HttpStatus.NOT_ACCEPTABLE);
        }

        return ResultData.success();
    }

    /**
     * 获取当前登录人信息
     *
     * @param request
     * @return
     */
    @Override
    public ResultData currentUserInfo(HttpServletRequest request) {
        CurrentUserInfoBO currentUserInfoBO = systemUserComponent.loginUserInfo(request);
        if (currentUserInfoBO == null) {
            throw new BusinessException("未登录登录", HttpStatus.UNAUTHORIZED);
        }
        CurrentUserInfoRsp currentUserInfoRsp = new CurrentUserInfoRsp();
        BeanUtils.copyProperties(currentUserInfoBO, currentUserInfoRsp);
        return ResultData.success(currentUserInfoRsp);
    }

    /**
     * 登出
     *
     * @param request
     * @return
     */
    @Override
    public ResultData loginOut(HttpServletRequest request) throws NoSuchAlgorithmException {
        systemUserComponent.loginOut(request);
        return ResultData.success();
    }

    /**
     * 激活
     *
     * @return
     */
    @Override
    @Transactional
    public ResultData activate(HttpServletRequest request, ActivateReq activateReq) throws NoSuchAlgorithmException {
        String userAccount = activateReq.getAccount();
        if (null == userAccount) {
            throw new BusinessException("请输入账号", HttpStatus.BAD_REQUEST);
        }

        String password = activateReq.getPassword();
        String repeatPassword = activateReq.getRepeatPassword();
        if (null == password || null == repeatPassword) {
            throw new BusinessException("请输入密码", HttpStatus.BAD_REQUEST);
        }
        if (!password.equals(repeatPassword)) {
            throw new BusinessException("两次输入密码不一致", HttpStatus.BAD_REQUEST);
        }

        // 检查登录状态
        CurrentUserInfoBO currentUserInfoBO = systemUserComponent.loginUserInfo(request);
        if (null == currentUserInfoBO) {
            throw new BusinessException("请先登录", HttpStatus.UNAUTHORIZED);
        }
        if (!currentUserInfoBO.getUserAccount().equals(userAccount)) {
            throw new BusinessException("只能激活当前登录账号", HttpStatus.FORBIDDEN);
        }

        // 检查账号状态
        SystemUserPO systemUserPO = systemUserMapper.queryByAccount(userAccount);
        if (null == systemUserPO) {
            throw new BusinessException("账户不存在", HttpStatus.BAD_REQUEST);
        }
        if (!(SystemUserStatusEnum.RETESTED.getCode() == systemUserPO.getUserStatus()
                || SystemUserStatusEnum.UNACTIVATED.getCode() == systemUserPO.getUserStatus())) {
            throw new BusinessException("请勿重复激活", HttpStatus.BAD_REQUEST);
        }

        systemUserComponent.setPassword(password, systemUserPO);
        systemUserPO.setUserStatus(SystemUserStatusEnum.OK.getCode());
        systemUserMapper.updateById(systemUserPO);

        // 修改当前登录人账号状态
        systemUserComponent.loginSuccess(request, systemUserPO);
        return ResultData.success();
    }


}